//
//  JCLBaseViewController.swift
//  WeiBo
//
//  Created by DDC on 2017/9/6.
//  Copyright © 2017年 DDC. All rights reserved.
//

import UIKit

class JCLBaseViewController: UIViewController {

    
    
    // MARK:  - 懒加载
    lazy var navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: UIScreen.hm_screenWidth(), height: 64))
    
    lazy var navItem = UINavigationItem()
    
    var tableView:UITableView?
    
    var refreshControl:JCLRefreshControl?
    
    var isPullUp = false
    
    var visitorInfoDictionary:[String: String]?

    
    override func viewDidLoad() {
        super.viewDidLoad()
       
        setUpUI()
        
        //判断是否登录状态
        JCLNetWorkTools.shared.userLogon ? loadData() : ()
        //注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(oAuthSuccessedLogin), name: NSNotification.Name(rawValue: JCLUserOAuthSuccessedNotificaton), object: nil)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    /// 重写title 的setter方法
    override var title: String?{
        didSet {
            navItem.title = title
        }
    }
    
    //添加数据
    func loadData(){
        
        //如果子类不做任何操作 默认关闭刷新控件
        //自动开启刷新
        refreshControl?.beginRefreshing()
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
            //1s之后关闭刷新
            self.refreshControl?.endRefreshing()
        }
    }
}
// MARK: - 按钮点击事件
extension JCLBaseViewController {
    
    @objc fileprivate func login() {
        print(#function)
        //发送通知
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: JCLUserShouldLoginNotification), object: nil)
        
    }
    @objc fileprivate  func register() {
        print(#function)
    }
    @objc fileprivate func oAuthSuccessedLogin (n:Notification ) {
        
        //登录成功之后 清除导航栏授权界面按钮
        navItem.leftBarButtonItem = nil
        navItem.rightBarButtonItem = nil
        
        // view = nil  会重新加载loadView--> viewDidLoad
        view = nil
        //再次加载viewdidload方法之后会重新发送通知,再次移除通知
        NotificationCenter.default.removeObserver(self)
    }
    
}

extension JCLBaseViewController {
    // MARK:  - 设置UI
   fileprivate func setUpUI (){
        
        view.backgroundColor = UIColor.white
        
        automaticallyAdjustsScrollViewInsets = false
        
        setUpNavBar()
        
        JCLNetWorkTools.shared.userLogon ? setUpTableView():setUpVisitorView()
        
        
    }
    
    // MARK:  - 设置访客视图
    fileprivate func setUpVisitorView(){
        
        let visitorView = JCLVisitorView(frame: view.bounds)

        view.insertSubview(visitorView, belowSubview: navigationBar)
        
        visitorView.visitorInfo = visitorInfoDictionary
        
        visitorView.loginButton .addTarget(self, action: #selector(login), for: .touchUpInside)
        visitorView.registerButton.addTarget(self, action: #selector(register), for: .touchUpInside)
        
        navItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: .plain, target: self, action: #selector(register))
        navItem.rightBarButtonItem = UIBarButtonItem(title: "登录", style: .plain, target: self, action: #selector(login))
        
    }
    // MARK:  -  设置导航条
    func setUpNavBar (){
        
        view.addSubview(navigationBar)
        
        navigationBar.items = [navItem]
        //设置导航栏的背景颜色
        navigationBar.barTintColor = UIColor.hm_color(withHex: 0xF6F6F6)
        
        //设置导航栏中间字体颜色
        navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.darkGray]
        
        //设置导航栏按钮字体颜色
        navigationBar.tintColor = UIColor.orange
        
    }
    // MARK:  - 设置tableView
    func setUpTableView() {
        
        tableView = UITableView(frame: view.bounds, style: .plain)
        
        tableView?.delegate = self
        tableView?.dataSource = self
        tableView?.contentInset = UIEdgeInsets(
                                      top: navigationBar.bounds.height,
                                      left: 0,
                                      bottom: tabBarController?.tabBar.bounds.height ?? 49,
                                      right: 0)
        view.insertSubview(tableView!, belowSubview: navigationBar)
        //实例化控件
        refreshControl = JCLRefreshControl()
        
        tableView?.addSubview(refreshControl!)
        
        //进度条缩进
        tableView?.scrollIndicatorInsets = tableView!.contentInset
        //添加监听方法
        refreshControl?.addTarget(self, action: #selector(loadData), for: .valueChanged)
        
    }
    
    
}

// MARK:  - tableView 数据源方法
extension JCLBaseViewController:UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        return UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        let section = tableView.numberOfSections - 1
        let row = indexPath.row
        
        if row < 0 || section < 0 {
            
            return
        }
        let count = tableView.numberOfRows(inSection: section)
        
        if row == count - 1 && !isPullUp {

            isPullUp = true
            
            loadData()
            
        }
    
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 10
    }
    
}
